package cn.net.autocode.platform.qbe;

import cn.hutool.core.util.StrUtil;
import cn.net.autocode.core.bean.ResultT;
import cn.net.autocode.core.utils.TreeUtils;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.dbManager.IdWorker;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
@RequestMapping("/platform/qbe")
public class PlatformQbeCtrl {
    private final Dao dictDao;

    public PlatformQbeCtrl(@Qualifier("dictDao") Dao dictDao) {
        this.dictDao = dictDao;
    }


    @RequestMapping("funcCategory")
    public ResultT funcCategory(){
        JSONArray arrays = new JSONArray();
        JSONArray categorys = dictDao.queryJSONArray("select * from ac_category where type='category' order by code");
        for(int i=0;i<categorys.size();i++){
            JSONObject category = categorys.getJSONObject(i);
            category.put("id","category_"+category.getString("code"));
            category.put("parentId", "0");
            category.put("value",category.getString("code"));
        }
        arrays.addAll(categorys);
        JSONArray applications = dictDao.queryJSONArray("select * from ac_category where type='application' order by code");
        arrays.addAll(applications);
        int len=applications.size();
        for(int i=0;i<len;i++){
            JSONObject application = applications.getJSONObject(i);
            application.put("id","application_"+application.getString("code"));
            application.put("parentId","category_"+application.getString("parentCode"));
            application.put("label",application.getString("code"));
            application.put("value",application.getString("code"));
        }
        return ResultT.success(TreeUtils.commonTree(arrays));
    }

    @RequestMapping("load")
    public ResultT load(){
        JSONArray arrays = new JSONArray();
        JSONArray categorys = dictDao.queryJSONArray("select * from ac_datasource_category where type='category' order by code");
        for(int i=0;i<categorys.size();i++){
            JSONObject category = categorys.getJSONObject(i);
            category.put("id","category_"+category.getString("code"));
            category.put("parentId", "0");
        }
        arrays.addAll(categorys);
        JSONArray applications = dictDao.queryJSONArray("select * from ac_datasource_category where type='application' order by code");
        arrays.addAll(applications);
        int len=applications.size();
        for(int i=0;i<len;i++){
            JSONObject application = applications.getJSONObject(i);
            application.put("id","application_"+application.getString("code"));
            application.put("parentId","category_"+application.getString("parentCode"));
            application.put("label",application.getString("code"));
        }

        JSONArray pageArrays = dictDao.queryJSONArray("select id,code,label,category_code  from ac_data_source order by category_code,code");
        int len2=pageArrays.size();
        for(int i=0;i<len2;i++){
            JSONObject page = pageArrays.getJSONObject(i);
            page.put("parentId","application_"+page.getString("categoryCode"));
            page.put("type","datasource");
            page.put("isLeaf",true);
            page.put("label",page.getString("code"));
        }
        arrays.addAll(pageArrays);
        return ResultT.success(TreeUtils.commonTree(arrays));
    }

    @RequestMapping("querySqlDetail")
    public ResultT querySqlDetail(@RequestBody JSONObject param){
        JSONObject data = dictDao.queryJSON("select * from ac_data_source where id=?",param.getString("id"));
        return ResultT.success(data);
    }

    @RequestMapping("add")
    @Transactional("dictTxManager")
    public ResultT add(@RequestBody JSONObject param){

        if(StrUtil.isBlank(param.getString("id"))){
            JSONArray categoryCode = param.getJSONArray("categoryCode");
            String category = categoryCode.getString(0);
            String application = categoryCode.getString(1);
            int num1 = dictDao.queryValue("select count(*) from ac_datasource_category where code=? and type='category'",Integer.class,category);
            if(num1==0){
                String label = dictDao.queryValue("select label from ac_category where code=? and type='category'",String.class,category);
                dictDao.executeUpdate("insert into ac_datasource_category(code,type,label,parent_code) values(?,?,?,?)",category,"category",label,"0");
                dictDao.executeUpdate("insert into ac_datasource_category(code,type,label,parent_code) values(?,?,?,?)",application,"application","",category);
            }else{
                int num2 = dictDao.queryValue("select count(*) from ac_datasource_category where code=? and type='application'",Integer.class,application);
                if (num2==0){
                    dictDao.executeUpdate("insert into ac_datasource_category(code,type,label,parent_code) values(?,?,?,?)",application,"application","",category);
                }
            }

            int num = dictDao.queryValue("select count(*) from ac_data_source where low_code=? and category_code=?",Integer.class,param.getString("code").toLowerCase().trim(),application);
            if(num>0){
                return ResultT.fail(param.getString("code")+"已存在，不能重复添加！");
            }
            param.put("categoryCode",application);
            param.put("lowCode",param.getString("code").toLowerCase().trim());
            param.put("id", IdWorker.ulid());
            dictDao.createJSON(param,"ac_data_source");
        }else{
            dictDao.updateJSON(param,"ac_data_source");
        }
        return ResultT.success(param);
    }

    @RequestMapping("changeCategory")
    public ResultT changeCategory(@RequestBody JSONObject param){
        JSONArray categoryCode = param.getJSONArray("categoryCode");
        String category = categoryCode.getString(0);
        String application = categoryCode.getString(1);
        int num1 = dictDao.queryValue("select count(*) from ac_datasource_category where code=? and type='category'",Integer.class,category);
        if(num1==0){
            String label = dictDao.queryValue("select label from ac_category where code=? and type='category'",String.class,category);
            dictDao.executeUpdate("insert into ac_datasource_category(code,type,label,parent_code) values(?,?,?,?)",category,"category",label,"0");
            dictDao.executeUpdate("insert into ac_datasource_category(code,type,label,parent_code) values(?,?,?,?)",application,"application","",category);
        }else{
            int num2 = dictDao.queryValue("select count(*) from ac_datasource_category where code=? and type='application'",Integer.class,application);
            if (num2==0){
                dictDao.executeUpdate("insert into ac_datasource_category(code,type,label,parent_code) values(?,?,?,?)",application,"application","",category);
            }
        }
        dictDao.executeUpdate("update ac_data_source set category_code=? where id=?",application,param.getString("id"));

        dictDao.executeUpdate("delete from ac_datasource_category t1 where type='application' and not exists(select 1 from ac_data_source t2 where t1.code=t2.category_code)");

        List<String> list =  dictDao.queryListValue("select distinct parent_code from ac_datasource_category where type='application'",String.class);
        if(list.isEmpty()){
            dictDao.executeUpdate("delete from ac_datasource_category");
        }else{
            dictDao.executeUpdate("delete from ac_datasource_category t1 where type='category' and code not in (?)",list);
        }
        return ResultT.success();
    }

    @RequestMapping("delete")
    @Transactional("dictTxManager")
    public ResultT delete(@RequestBody JSONObject param){
        dictDao.executeUpdate("delete from ac_data_source where id=?",param.getString("id"));
        dictDao.executeUpdate("delete from ac_data_source_param where datasource_id=?",param.getString("id"));
        dictDao.executeUpdate("delete from ac_data_source_dc where datasource_id=?",param.getString("id"));

        //删除目录
        dictDao.executeUpdate("delete from ac_datasource_category t1 where type='application' and not exists(select 1 from ac_data_source t2 where t1.code=t2.category_code)");

        List<String> list =  dictDao.queryListValue("select distinct parent_code from ac_datasource_category where type='application'",String.class);
        if(list.isEmpty()){
            dictDao.executeUpdate("delete from ac_datasource_category");
        }else{
            dictDao.executeUpdate("delete from ac_datasource_category t1 where type='category' and code not in (?)",list);
        }

        return ResultT.success();
    }

    @RequestMapping("saveParam")
    public ResultT saveParam(@RequestBody JSONObject param){
        if(StrUtil.isBlank(param.getString("id"))){
            int sortNo = dictDao.maxSort("select max(sort_no) from ac_data_source_param where datasource_id=?",param.getString("datasourceId"));
            param.put("id", IdWorker.ulid());
            param.put("sortNo",sortNo);
            if("Y".equals(param.getString("isWhere"))){
                param.put("isWhere","Y");
            }else{
                param.put("isWhere","N");
            }
            dictDao.createJSON(param,"ac_data_source_param");
        }else{
            dictDao.updateJSON(param,"ac_data_source_param");
        }
        return ResultT.success(param);
    }

    @RequestMapping("queryParams")
    public ResultT queryParams(@RequestBody JSONObject param){
        JSONArray array = dictDao.queryJSONArray("select * from ac_data_source_param where datasource_id=? order by sort_no",param.getString("datasourceId"));
        return ResultT.success(array);
    }

    @RequestMapping("delParam")
    public ResultT delParam(@RequestBody JSONObject param){
        dictDao.executeUpdate("delete from ac_data_source_param where id=?",param.getString("id"));
        return ResultT.success();
    }

    @RequestMapping("changeParam/{fieldName}")
    public ResultT changeParam(@PathVariable("fieldName") String fieldName, @RequestBody JSONObject param){
        if("sortNo".equals(fieldName)){
            dictDao.executeUpdate("update ac_data_source_param set sort_no=? where id=?",param.getIntValue("sortNo"),param.getString("id"));
        }else if("operType".equals(fieldName)){
            dictDao.executeUpdate("update ac_data_source_param set oper_type=? where id=?",param.getString("operType"),param.getString("id"));
        }
        return ResultT.success();
    }

    @RequestMapping("queryResultConversion")
    public ResultT queryResultConversion(@RequestBody JSONObject param){
        JSONArray array = dictDao.queryJSONArray("select * from ac_data_source_dc where datasource_id=? order by field_name",param.getString("datasourceId"));
        return ResultT.success(array);
    }

    @RequestMapping("saveResultConversion")
    public ResultT saveResultConversion(@RequestBody JSONObject param){
        String fieldName = param.getString("fieldName").toLowerCase().trim();
        param.put("fieldName",fieldName);
        if(StrUtil.isBlank(param.getString("id"))){
            param.put("id", IdWorker.ulid());
            dictDao.createJSON(param,"ac_data_source_dc");
        }else{
            dictDao.updateJSON(param,"ac_data_source_dc");
        }
        return ResultT.success(param);
    }

    @RequestMapping("delResultConversion")
    public ResultT delResultConversion(@RequestBody JSONObject param){
        dictDao.executeUpdate("delete from ac_data_source_dc where id=?",param.getString("id"));
        return ResultT.success();
    }

    @RequestMapping("changeResultConversion/{fieldName}")
    public ResultT changeResultConversion(@PathVariable("fieldName") String fieldName, @RequestBody JSONObject param){
        if("resultType".equals(fieldName)){
            dictDao.executeUpdate("update ac_data_source_dc set result_type=? where id=?",param.getString("resultType"),param.getString("id"));
        }else if("fieldName".equals(fieldName)){
            dictDao.executeUpdate("update ac_data_source_dc set field_name=? where id=?",param.getString("fieldName"),param.getString("id"));
        }
        return ResultT.success();
    }





}
